// 导入Vue Router的创建路由器函数
import { createRouter, createWebHistory } from "vue-router";
import { ElMessage } from "element-plus";

// 导入页面组件
import WebDesign from "../views/WebDesign/Index.vue";
import Login from "../views/Login/Index.vue";
import Home from "../views/Home/Index.vue";
// 导入认证store
import { useAuthStore } from "@/stores/auth";

// 定义路由配置
const routes = [
  {
    path: "/login",
    name: "Login",
    component: Login,
    meta: {
      title: "WeMaster™ - 登录",
      requiresAuth: false,
    },
  },
  {
    path: "/",
    redirect: "/weDesign",
  },
  {
    path: "/weDesign",
    name: "WebDesign",
    component: WebDesign,
    meta: {
      title: "WeMaster™ - WebDesign",
      requiresAuth: true,
      menu: {
        title: "WeDesign",
        icon: "Opportunity",
        order: 2,
        showInMenu: true,
      },
    },
    children: [
      {
        path: "details",
        name: "Details",
        component: () => import("../views/WebDesign/Details.vue"),
        meta: {
          title: "WeMaster™ - Digital Asset Details",
          requiresAuth: true,
          menu: {
            title: "Digital Asset Details",
            icon: "ChatLineRound",
            showInMenu: false,
          },
        },
      },
    ],
  },
  
  {
    path: "/home",
    name: "Home",
    component: Home,
    meta: {
      title: "WeMaster™ - Home",
      requiresAuth: true,
      menu: {
        title: "Home",
        icon: "house",
        order: 1,
        hideBread:true,
        showInMenu: true,
      },
    },
  },
  {
    path: "/weProvide",
    name: "WeProvide",
    component: () => import("../views/WeProvide/Index.vue"),
    meta: {
      title: "WeMaster™ - WeProvide",
      requiresAuth: true,
      menu: {
        title: "WeProvide",
        icon: "DataAnalysis",
        order: 1,
        showInMenu: true,
      },
    },
  },
  {
    path: "/weAnnotate",
    name: "WeAnnotate",
    meta: {
      title: "WeMaster™ - WeAnnotate",
      requiresAuth: true,
      menu: {
        title: "WeAnnotate",
        icon: "EditPen",
        order: 3,
        showInMenu: true,
      },
    },
    children: [
      {
        path: "levelList",
        name: "LevelList",
        component: () => import("../views/WeAnnotate/LevelList.vue"),
        meta: {
          title: "WeMaster™ - Level List",
          requiresAuth: true,
          menu: {
            title: "Level List",
            icon: "List",
            showInMenu: true,
          },
        },
      },
      {
        path: "annotation",
        name: "Annotation",
        component: () => import("../views/WeAnnotate/Annotation.vue"),
        meta: {
          title: "WeMaster™ - Annotation",
          requiresAuth: true,
          menu: {
            title: "Annotation",
            icon: "Edit",
            showInMenu: true,
          },
        },
      },
    ],
  },
  {
    path: "/weCurate",
    name: "WeCurate",
    meta: {
      title: "WeMaster™ - WeCurate",
      requiresAuth: true,
      menu: {
        title: "WeCurate",
        icon: "EditPen",
        order: 4,
        showInMenu: true,
      },
    },
    children: [
      {
        path: "systematicLearning",
        name: "SystematicLearning",
        meta: {
          title: "WeMaster™ - Systematic Learning",
          requiresAuth: true,
          menu: {
            title: "Systematic Learning",
            icon: "List",
            showInMenu: true,
          },
        },
        children: [
          {
            path: "bundle",
            name: "Bundle",
            component: () =>
              import("../views/WeCurate/SystematicLearning/Bundle.vue"),
            meta: {
              title: "WeMaster™ - Bundle",
              requiresAuth: true,
              menu: {
                title: "Bundle",
                icon: "Edit",
                showInMenu: true,
              },
            },
          },
          {
            path: "Create",
            name: "Create",
            component: () =>
              import("../views/WeCurate/SystematicLearning/Create.vue"),
            meta: {
              title: "WeMaster™ - Create",
              requiresAuth: true,
              menu: {
                title: "Create",
                showInMenu: false,
              },
            },
          },
          {
            path: "CreateShortCourse",
            name: "CreateShortCourse",
            component: () =>
              import("../views/WeCurate/SystematicLearning/CreateShortCourse.vue"),
            meta: {
              title: "WeMaster™ - CreateShortCourse",
              requiresAuth: true,
              menu: {
                title: "CreateShortCourse",
                showInMenu: false,
              },
            },
          },
          {
            path: "shortCourse",
            name: "ShortCourse",
            component: () =>
              import("../views/WeCurate/SystematicLearning/ShortCourse.vue"),
            meta: {
              title: "WeMaster™ - ShortCourse",
              requiresAuth: true,
              menu: {
                title: "Short Course",
                icon: "Edit",
                showInMenu: true,
              },
            },
          },
          {
            path: "Micro Credential",
            name: "MicroCredential",
            component: () =>
              import("../views/WeCurate/SystematicLearning/MicroCredential.vue"),
            meta: {
              title: "WeMaster™ - MicroCredential",
              requiresAuth: true,
              menu: {
                title: "Micro Credential",
                icon: "Edit",
                showInMenu: true,
              },
            },
          },
            {
            path: "CreateMicroCredential",
            name: "CreateMicroCredential",
            component: () =>
              import("../views/WeCurate/SystematicLearning/CreateMicroCredential.vue"),
            meta: {
              title: "WeMaster™ - CreateMicroCredential",
              requiresAuth: true,
              menu: {
                title: "CreateMicroCredential",
                icon: "Edit",
                showInMenu: false,
              },
            },
          },
        ],
      },
      {
        path: "On-demandLearning",
        name: "On-demandLearning",
        meta: {
          title: "WeMaster™ -On-demand Learning",
          requiresAuth: true,
          menu: {
            title: "On-demand Learning",
            icon: "List",
            showInMenu: true,
          },
        },
        children: [
          {
            path: "LearningPath",
            name: "LearningPath",
            component: () =>
              import("../views/WeCurate/On-demandLearning/LearningPath.vue"),
            meta: {
              title: "WeMaster™ - LearningPath",
              requiresAuth: true,
              menu: {
                title: "Learning Path",
                icon: "Edit",
                showInMenu: true,
              },
            },
          },
          {
            path: "CreateLearningPath",
            name: "CreateLearningPath",
            component: () =>
              import("../views/WeCurate/On-demandLearning/CreateLearningPath.vue"),
            meta: {
              title: "WeMaster™ - CreateLearningPath",
              requiresAuth: true,
              menu: {
                title: "CreateLearningPath",
                icon: "Edit",
                showInMenu: false,
              },
            },
          },
        ],
      },
    ],
  },
  {
    // 404页面重定向到WebDesign
    path: "/:pathMatch(.*)*",
    redirect: "/weDesign",
  },
];

// 创建路由器实例
const router = createRouter({
  // 使用HTML5 History模式
  history: createWebHistory(),
  routes,
});

// 路由守卫 - 在每次路由跳转前执行
router.beforeEach(async (to, _from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title;
  }

  // 获取认证store
  const authStore = useAuthStore();

  // 初始化认证状态（仅在首次访问时）
  if (!authStore.token && !authStore.userInfo) {
    authStore.initAuth();
  }

  // 检查路由是否需要认证
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth);

  if (requiresAuth) {
    // 需要认证的路由
    if (!authStore.isAuthenticated) {
      // 未登录，跳转到登录页
      ElMessage.warning("请先登录");
      next({
        path: "/login",
        query: { redirect: to.fullPath },
      });
      return;
    }

    // 检查token是否即将过期
    if (authStore.checkTokenExpiry()) {
      try {
        const refreshResult = await authStore.refreshToken();
        if (!refreshResult.success) {
          // 刷新失败，跳转到登录页
          ElMessage.error("登录已过期，请重新登录");
          next({
            path: "/login",
            query: { redirect: to.fullPath },
          });
          return;
        }
      } catch (error) {
        console.error("Token刷新失败:", error);
        ElMessage.error("登录已过期，请重新登录");
        next({
          path: "/login",
          query: { redirect: to.fullPath },
        });
        return;
      }
    }
  } else {
    // 不需要认证的路由
    if (to.path === "/login" && authStore.isAuthenticated) {
      // 已登录用户访问登录页，重定向到首页
      next("/");
      return;
    }
  }

  next();
});

// 导出路由器实例
export default router;
